<?php

namespace app\common\model\user;

use think\Model;


class Address extends Model
{

    

    

    // 表名
    protected $name = 'user_address';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'state_text'
    ];
    

    
    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

          /**
     * 设置用户默认地址
     * @param int  $uid
     * @return array
     */
    public static function setDefaultAddress($id, $uid)
    {
        self::where('user_id', $uid)->update(['is_default' => 0]);
        return self::where('user_id', $uid)->where('id', $id)->update(['is_default' => 1]);
    }

    /**
     * 获取默认地址
     * @param int  $uid
     * @return array
     */
    public static function getDefaultAddress($uid)
    {
        return self::where('is_default', 1)->where('user_id', $uid)->find();
    }
    /**
     * 获取用户收货地址
     * @param int  $uid
     * @return array
     */
    public static function getUserAddress($uid,$limit=10)
    {
        return self::where('user_id', $uid)->paginate($limit)->toArray();
    }

    /**
     * 用户添加收货地址
     * @param int  $uid
     * @return array
     */
    public static function AddAddress($data)
    {
        if ($data['is_default'] == 1) {
            self::where('user_id', $data['user_id'])->update(['is_default' => 0]);
        }
        $model = new self();
        if (isset($data['id'])) {
            $model->get($data['id']);
            return $model->isUpdate(true)->save($data);
        }
        return $model->allowField(true)->save($data);
    }

    /**
     * 删除收货地址
     * @param int  $uid
     * @return array
     */
    public static function delAddress($id, $uid)
    {

        return self::where('id', $id)->where('user_id', $uid)->delete();
    }
}
